package com.wll.design.策略.service.impl;

import com.wll.design.策略.service.IPay;
import com.wll.design.core.annotation.PayCode;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 注解写法
 * @Author: Wanglulu
 * @Date: 2021/1/4 10:46
 * @Version 0.0.1
 */
@Service
public class PayServiceImplAnnotation implements ApplicationListener<ContextRefreshedEvent> {

    private static Map<String, IPay> payMap = null;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(PayCode.class);
        if (beansWithAnnotation != null) {
            payMap = new HashMap<>();
            beansWithAnnotation.forEach((key, value) -> {
                String code = value.getClass().getAnnotation(PayCode.class).code();
                payMap.put(code, (IPay) value);
            });
        }
    }

    public void toPay(String code) {
        IPay iPay = payMap.get(code);
        if (iPay != null) {
            iPay.pay();
        } else {
            System.out.println("没有用该支付方式：" + code);
        }
    }


}
